package com.blast.cn.ui

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.widget.AdapterView
import com.blast.cn.AppMainActivity
import com.blast.cn.R
import com.blast.cn.http.MainHttps
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.LoadingPopupView
import com.wxl.common.AppConstant
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.http.CommonHttpUtil
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.room.entity.CollectorBean
import com.wxl.common.room.entity.DetonatorEntity
import com.wxl.common.room.entity.UserEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.*
import kotlinx.android.synthetic.main.activity_login_layout.*

class LoginActivity : AbsActivity() {

    private var loadingPop: LoadingPopupView? = null
    private var keyCodeF2 = false
    private var keyCodeF3 = false

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_login_layout
    }

    override fun onCreateViewChanged() {

        setTopTitle("登录")

        loginAccountEt.setText(AppContext.appContext.getLoginAccount())

        DBHelper.queryUser(object :
            ObservableUtil.Companion.OnNextCallback<List<UserEntity>>() {
            override fun onNext(t: List<UserEntity>) {
                if (t.isNotEmpty()) {
                    val data = arrayListOf<String>()
                    t.forEach {
                        data.add(it.idcode)
                    }
                    loginAccountEt.show(
                        data,
                        DPUtil.dip2px(400),
                        AdapterView.OnItemClickListener { parent, view, position, id ->
                            loginAccountEt.setText(data[position])
                        })
                }
            }
        })


        loginBtn.setOnClickListener {
            doLogin()
        }

        aetWatch = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                checkSubmit()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        }


        petWatch = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                checkSubmit()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        }


        loginAccountEt.addTextChangedListener(aetWatch)
        loginPwdEt.addTextChangedListener(petWatch)
    }




    private lateinit var aetWatch: TextWatcher
    private lateinit var petWatch: TextWatcher


    private fun checkSubmit() {
        loginBtn.isSelected = false
        if (TextUtils.isEmpty(loginAccountEt.text) || TextUtils.isEmpty(loginPwdEt.text)) {
            loginBtn.setBackgroundResource(R.drawable.gray_login_btn_selector)
            return
        }

        if (loginAccountEt.text!!.length == 18) {
            loginBtn.setBackgroundResource(R.drawable.yellow_login_btn_selector)
        }
    }


    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (loadingPop == null || !loadingPop!!.isShow) {
                finish()
            }
        } else if (keyCode == KeyEvent.KEYCODE_F2) {
            keyCodeF2 = true
            checkPressDownF2F3()
        } else if (keyCode == KeyEvent.KEYCODE_F3) {
            keyCodeF3 = true
            checkPressDownF2F3()
        }
        return true
    }


    private fun checkPressDownF2F3() {
        if (keyCodeF2 && keyCodeF3) {
            startActivity(Intent(this, DeviceInfoActivity::class.java))
        } else {
            ObservableUtil.delay(200, Runnable {
                keyCodeF2 = false
                keyCodeF3 = false
            })
        }
    }


    private fun doLogin() {
        if (TextUtils.isEmpty(loginAccountEt.text)) {
            Toll.toll("请输入账户")
            return
        }

        if (loginAccountEt.text!!.length != 18) {
            Toll.toll("请输入正确的身份证号")
            return
        }

        if (TextUtils.isEmpty(loginPwdEt.text)) {
            Toll.toll("请输入密码")
            return
        }


        loadingPop = XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asLoading()

        addPop(loadingPop as BasePopupView)

        KeyBoardUtil.hideSoftInput(loginAccountEt)
        KeyBoardUtil.hideSoftInput(loginPwdEt)

        loadingPop?.show()

        if (NetWorkUtils.isNetWorkAvailable(AppContext.appContext.getApplication())) {
            MainHttps.login(
                loginAccountEt.text.toString(),
                loginPwdEt.text.toString(),
                object : SerialHttpCallback<UserEntity>("Obj") {
                    override fun loadDataSuccess(datas: ArrayList<UserEntity>) {
                        if (datas.isNotEmpty()) {
                            AppContext.appContext.saveLoginAccount(loginAccountEt.text.toString())
                            AppContext.appContext.saveLoginName(datas[0].name)
                            AppContext.appContext.saveLoginAcc(datas[0])
                            datas[0].loginTime = System.currentTimeMillis()
                            datas[0].userpass = StringUtils.string2MD5(loginPwdEt.text.toString())
                            DBHelper.insertUser(object :
                                ObservableUtil.Companion.OnNextCallback<Boolean>() {
                                override fun onNext(t: Boolean) {
                                    loginSuccess()
                                }
                            }, datas[0])
                        }
                    }

                    override fun loadDataFailed(e: Throwable) {
                        loadingPop?.dismiss()
                        if (!TextUtils.isEmpty(e.message)) {
                            Toll.toll(e.message!!)
                        }
                    }

                })
        } else {
            unLineAvailableLogin()
        }

    }


    /**
     * 离线验证登录
     */
    private fun unLineAvailableLogin() {
        DBHelper.queryUserById(loginAccountEt.text.toString(),
            object : ObservableUtil.Companion.OnNextCallback<List<UserEntity>>() {
                override fun onNext(t: List<UserEntity>) {
                    if (t.isNullOrEmpty()) {
                        //  Toll.toll("网络不可用！")
                        loadingPop?.dismiss()
                    } else {
                        t.forEach {
                            if (TextUtils.equals(loginAccountEt.text.toString(), it.idcode)) {
                                unLineAvailablePwdLogin(it)
                                return
                            }
                        }
                        loadingPop?.dismiss()
                        Toll.toll("网络不可用！")
                    }
                }
            })
    }

    /**
     * 离线验证密码
     */
    private fun unLineAvailablePwdLogin(user: UserEntity) {
        if (user.loginTime < System.currentTimeMillis() - AppConstant.mLoginLimitTime) {
            Toll.toll("网络不可用！")
            loadingPop?.dismiss()
        } else {
            val md5Pwd = StringUtils.string2MD5(loginPwdEt.text.toString())
            if (TextUtils.equals(md5Pwd, user.userpass)) {
                loginSuccess()
            } else {
                loadingPop?.dismiss()
                Toll.toll("离线登陆，密码不匹配！")
            }
        }
    }


    /**
     * 登录成功
     */
    private fun loginSuccess() {
        CommonHttpUtil.getDetonatorInfo(object :
            ObservableUtil.Companion.OnNextCallback<DetonatorEntity>() {
            override fun onNext(t: DetonatorEntity) {
                loginBqText.text = "版权所有：${t.deptid}"
                loadCollector()
            }

            override fun error(e: Throwable) {
                loadCollector()
            }
        })
    }


    /**
     * 加载采集器信息
     */
    private fun loadCollector() {
        CommonHttpUtil.getCollectorInfo(object :
            ObservableUtil.Companion.OnNextCallback<List<CollectorBean>>() {
            override fun onNext(t: List<CollectorBean>) {
                loadingPop?.dismiss()
                loginEnd()
            }

            override fun error(e: Throwable) {
                loadingPop?.dismiss()
                loginEnd()
            }
        })
    }


    private fun loginEnd() {
        startActivity(Intent(this, AppMainActivity::class.java))
        finish()
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        KeyBoardUtil.hideSoftInput(loginAccountEt)
        KeyBoardUtil.hideSoftInput(loginPwdEt)
    }

    override fun onDestroy() {
        super.onDestroy()
        loginAccountEt.removeTextChangedListener(aetWatch)
        loginPwdEt.removeTextChangedListener(petWatch)
    }
}